import { BASE_URL } from "../../utils/config";
// index.ts
interface Course {
  id: number;
  courseName: string;
  icon: string;
  color: string;
  checkType: number;
  checkContent: string;
}

interface CalendarDay {
  day: number;
  isToday: boolean;
  isChecked: boolean;
  status: string;
  isCurrentMonth?: boolean;
  date?: string; // 完整的日期字符串
}

Page({
  data: {
    currentYear: new Date().getFullYear(),
    currentMonth: new Date().getMonth() + 1,
    calendarDays: [] as CalendarDay[],
    isClockIn: false,
    courses: [
    ] as Course[],
    currentCourse: {} as Course,
    dailyRecords: {} as Record<string, boolean>,
    selectDay: '',
    isScanning: false
  },
  onShow() {
    // 如果正在扫码中，不执行刷新逻辑
    if (this.data.isScanning) {
      return;
    }
    // 校验登录状态
    this.checkLogin();
    this.updateCalendar();

    // 设置日期范围
    const date = new Date();
    const startDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    this.setData({
      selectDay: startDate,
    });
    this.fetchCourseList(startDate);
    this.fetchCurrentCourse();

  },
  fetchCourseList(startDate: string) {
    const token = wx.getStorageSync('token')
    wx.request({
      url: `${BASE_URL}/course/checkList`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`
      },
      data: {
        leaveDate: startDate
      },
      success: (res: any) => {
        const { data } = res.data
        if (data) {
          const coursesWithColor = data.map((course: any) => ({
            ...course,
            color: `hsl(${Math.random() * 360}, 70%, 80%)`
          }));
          this.setData({
            courses: coursesWithColor
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取课程列表失败',
          icon: 'error'
        })
      }
    })
  },

  fetchCurrentCourse() {
    const token = wx.getStorageSync('token')
    wx.request({
      url: `${BASE_URL}/course/pullCourse`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`
      },
      data: {
      },
      success: (res: any) => {
        const { data } = res.data
        if (data) {
          this.setData({
            currentCourse: data
          })
          if(data.checkStatus === 1) {
            this.setData({
              isClockIn: true
            });
            return;
          } else if(data.checkStatus === 4) {
            wx.showToast({
              title: '已经请假',
              icon: 'error'
            })
            return;
          }
          wx.showModal({
            title: '当前课程',
            content: `${data.courseName}已经开始签到，是否现在进行签到？`,
            confirmText: '确认签到',
            cancelText: '稍后再说',
            success: (res) => {
              if (res.confirm) {
                this.handleClockIn();
              }
            }
          })
        } else {
          wx.showToast({
            title: '未到签到时间',
            icon: 'error'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取签到课程失败',
          icon: 'error'
        })
      }
    })
  },

  // 拍照
  takePhoto() {
    const camera = wx.createCameraContext();
    camera.takePhoto({
      quality: 'high',
      success: (res) => {
        // 这里可以处理拍照后的图片，比如上传到服务器
        console.log('拍照成功：', res.tempImagePath);
        this.setData({
          showCamera: false,
          isClockIn: true
        });
        wx.showToast({
          title: '打卡成功',
          icon: 'success'
        });
      },
      fail: (err) => {
        console.error('拍照失败：', err);
        wx.showToast({
          title: '拍照失败',
          icon: 'error'
        });
      }
    });
  },

  // 取消拍照
  cancelPhoto() {
    this.setData({ showCamera: false });
  },

  // 相机错误处理
  error(e: any) {
    console.error('相机错误：', e.detail);
    wx.showToast({
      title: '相机启动失败',
      icon: 'error'
    });
  },

  // 跳转到个人信息页面
  navigateToMy() {
    wx.navigateTo({
      url: '/pages/my/my'
    });
  },
  // 更新日历数据
  updateCalendar() {
    const date = new Date(this.data.currentYear, this.data.currentMonth - 1);
    const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
    const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
    const firstDayWeek = firstDay.getDay();
    const today = new Date();

    const days: CalendarDay[] = [];

    // 上个月的剩余天数
    const prevMonthLastDay = new Date(date.getFullYear(), date.getMonth(), 0).getDate();
    for (let i = 0; i < firstDayWeek; i++) {
      days.push({
        day: prevMonthLastDay - firstDayWeek + i + 1,
        isToday: false,
        isChecked: false,
        status: '-'
      });
    }

    // 当前月的天数
    for (let i = 1; i <= lastDay.getDate(); i++) {
      const dateStr = `${this.data.currentYear}-${String(this.data.currentMonth).padStart(2, '0')}-${String(i).padStart(2, '0')}`;
      days.push({
        day: i,
        isToday: today.getDate() === i && today.getMonth() === date.getMonth() && today.getFullYear() === date.getFullYear(),
        isChecked: this.data.dailyRecords[dateStr] || false,
        status: this.data.dailyRecords[dateStr] ? '已打卡' : '-',
        isCurrentMonth: true,
        date: dateStr
      });
    }

    // 下个月的开始天数
    const remainingDays = 42 - days.length;
    for (let i = 1; i <= remainingDays; i++) {
      days.push({
        day: i,
        isToday: false,
        isChecked: false,
        status: '-'
      });
    }

    this.setData({ calendarDays: days });
  },

  // 切换月份
  prevMonth() {
    let { currentYear, currentMonth } = this.data;
    if (currentMonth === 1) {
      currentYear--;
      currentMonth = 12;
    } else {
      currentMonth--;
    }
    this.setData({ currentYear, currentMonth }, () => {
      this.updateCalendar();
    });
  },

  nextMonth() {
    let { currentYear, currentMonth } = this.data;
    if (currentMonth === 12) {
      currentYear++;
      currentMonth = 1;
    } else {
      currentMonth++;
    }
    this.setData({ currentYear, currentMonth }, () => {
      this.updateCalendar();
    });
  },

  uploadFaceImage(imagePath: string) : Promise<any> {
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync('token');
      wx.uploadFile({
        url: `${BASE_URL}/file/upload`,
        filePath: imagePath,
        name: 'file',
        header: {
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {
          const data = JSON.parse(res.data);
          console.log("upload res data", data);
          resolve(data);
        },
        fail: () => {
          wx.showToast({
            title: '上传头像失败',
            icon: 'error'
          });
          reject(new Error('上传头像失败'));
        }
      });
    });
  },

  // 打卡功能
  handleClockIn() {
    // 检查是否已经打卡
    if (this.data.isClockIn) return;
      
    // 判断打卡类型
    if(this.data.currentCourse.checkType === 1) {
      // 直接打卡
      const token = wx.getStorageSync('token');
      wx.request({
        url: `${BASE_URL}/check/directSave`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`
        },
        data: {
          courseId: this.data.currentCourse.id
        },
        success: (res: any) => {
          const { code } = res.data;
          if (code === 200) {
            this.setData({
              isClockIn: true
            }, () => {
              wx.showToast({
                title: '打卡成功',
                icon: 'success'
              });
              this.fetchCourseList(this.data.selectDay);
            });
          } else {
            wx.showToast({
              title: res.data.msg || '打卡失败',
              icon: 'error'
            });
          }
        },
        fail: () => {
          wx.showToast({
            title: '打卡失败',
            icon: 'error'
          });
        }
      });
      return;
    } else if(this.data.currentCourse.checkType === 3) {
      this.qrcodeCheck();
      return;
    } else if(this.data.currentCourse.checkType === 4) {
      wx.navigateTo({
        url: `/pages/location/location?courseId=${this.data.currentCourse.id}`,
      });
      return;
    } else if(this.data.currentCourse.checkType === 5) {
      wx.navigateTo({
        url: `/pages/gesture/gesture?courseId=${this.data.currentCourse.id}`,
      });
      return;
    } else if(this.data.currentCourse.checkType === 2) {
      wx.navigateTo({
        url: `/pages/face/face?courseId=${this.data.currentCourse.id}`,
      });
      return;
    }
  },
  checkLogin() {
    const token = wx.getStorageSync('token');
    // 判断token是否存在，不存在，跳转到login页面
    if (!token) {
      wx.navigateTo({
        url: '/pages/login/login',
      });
    }
  },
  async qrcodeCheck() {
    try {
      const result = await this.scanQRCode();
      if(result == this.data.currentCourse.checkContent) {
        // 直接打卡
        const token = wx.getStorageSync('token');
        wx.request({
          url: `${BASE_URL}/check/qrcodeSave`,
          method: 'POST',
          header: {
            'Authorization': `Bearer ${token}`
          },
          data: {
            courseId: this.data.currentCourse.id
          },
          success: (res: any) => {
            const { code } = res.data;
            if (code === 200) {
              this.setData({
                isClockIn: true
              }, () => {
                wx.showToast({
                  title: '打卡成功',
                  icon: 'success'
                });
                this.fetchCourseList(this.data.selectDay);
              });
            } else {
              wx.showToast({
                title: res.data.msg || '打卡失败',
                icon: 'error'
              });
            }
          },
          fail: () => {
            wx.showToast({
              title: '打卡失败',
              icon: 'error'
            });
          }
        });
      } else {
        wx.showToast({
          title: '二维码内容不正确',
          icon: 'error'
        });
      }
    } catch (error) {
      console.error('扫描失败:', error);
      wx.showToast({
        title: '扫描失败',
        icon: 'error'
      });
      throw error;
    }
  },
  
  // 扫描二维码
  scanQRCode(): Promise<string> {
    // 设置扫码标记
    this.setData({ isScanning: true });
    return new Promise((resolve, reject) => {
      wx.scanCode({
        onlyFromCamera: true,
        scanType: ['qrCode'],
        success: (res) => resolve(res.result),
        fail: (error) => {
          // 扫码失败时重置标记
          this.setData({ isScanning: false });
          reject(error);
        },
        complete: () => {
          // 扫码完成时重置标记
          this.setData({ isScanning: false });
        }
      });
    });
  },

  // 点击日历日期
  onDayTap(e: WechatMiniprogram.CustomEvent) {
    const index = e.currentTarget.dataset.index;
    const selectedDay = this.data.calendarDays[index];
    
    if (selectedDay.isCurrentMonth) {
      // 更新选中状态
      const calendarDays = this.data.calendarDays.map((day, i) => ({
        ...day,
        isChecked: i === index
      }));
      
      this.setData({
        calendarDays
      });

      // 可以在这里处理选中日期后的逻辑
      console.log('选中日期:', selectedDay.date);
    }

    this.setData({
      selectDay: selectedDay.date!!,
    });
    this.fetchCourseList(selectedDay.date!!);
  }
});
